﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Q7.BevTree
{
    public class BevNodeLoop : BevNode
    {
        private int _loopCount = -1;
        private int _currentLoop;

        public BevNodeLoop(string debugName)
            : base(debugName)
        {
        }

        public BevNodeLoop SetLoopCount(int n)
        {
            _loopCount = n;
            return this;
        }

        protected override bool DoEvaluate(BevNodeInputParam input)
        {
            var checkLoop = (_loopCount == -1) || (_currentLoop < _loopCount);

            if (!checkLoop)
                return false;

            if (CheckIndex(0))
                if (Children[0].Evaluate(input))
                    return true;

            return false;
        }

        protected override int DoTick(BevNodeInputParam input, BevNodeOutputParam output)
        {
            var isFinish = BRS_FINISH;

            if (CheckIndex(0))
            {
                isFinish = Children[0].Tick(input, output);

                if (isFinish == BRS_FINISH)
                {
                    if (_loopCount == -1)
                        isFinish = BRS_EXECUTING;
                    else
                    {
                        ++_currentLoop;
                        if (_currentLoop < _loopCount)

                            isFinish = BRS_EXECUTING;
                    }
                }
            }

            if (isFinish == BRS_FINISH)
                _currentLoop = 0;

            return isFinish;
        }

        protected override void DoTransition(BevNodeInputParam input)
        {
            if (CheckIndex(0))
                Children[0].Transition(input);

            _currentLoop = 0;
        }
    }
}
